package io.adrainty.bolee.security.repository.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.adrainty.bolee.framework.commons.user.UserEntity;
import io.adrainty.bolee.security.mapper.IUserMapper;
import io.adrainty.bolee.security.mapper.IUserRoleMapper;
import io.adrainty.bolee.security.models.bo.DeptPostUserBO;
import io.adrainty.bolee.security.models.bo.UserBO;
import io.adrainty.bolee.security.models.bo.UserRoleBO;
import io.adrainty.bolee.security.repository.IDeptRepository;
import io.adrainty.bolee.security.repository.IUserRepository;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author AdRainty
 * @version V1.0.0
 * @since 2025/8/3 上午1:04
 */

@Repository
public class UserRepositoryImpl implements IUserRepository {

    @Resource
    private IUserMapper userMapper;

    @Resource
    private IUserRoleMapper userRoleMapper;

    @Resource
    private IDeptRepository deptRepository;

    @Override
    public IPage<UserEntity> findUserPage(UserEntity entity, Integer pageNum, Integer pageSize) {
        Page<UserBO> page = Page.of(pageNum, pageSize);
        Wrapper<UserBO> wrapper = getWrapper(entity);
        if (wrapper == null) return new Page<>(pageNum, pageSize);
        return userMapper.selectPage(page, wrapper).convert(item -> BeanUtil.toBean(item, UserEntity.class));
    }

    @Override
    public boolean updateUser(UserEntity entity) {
        UserBO userBO = BeanUtil.toBean(entity, UserBO.class);
        boolean result = userMapper.updateById(userBO) > 0;
        if (!result) return false;
        BeanUtil.copyProperties(userBO, entity);
        return true;
    }

    @Override
    public List<UserEntity> listUser(UserEntity entity) {
        Wrapper<UserBO> wrapper = getWrapper(entity);
        if (wrapper == null) return List.of();
        List<UserBO> result = userMapper.selectList(wrapper);
        return BeanUtil.copyToList(result, UserEntity.class);
    }

    @Nullable
    @Override
    public UserEntity findByUsername(String username, String company) {
        if (StringUtils.isBlank(username)) return null;
        Wrapper<UserBO> wrapper = Wrappers.lambdaQuery(UserBO.class)
                .eq(UserBO::getUsername, username)
                .eq(UserBO::getCompanyNo, company);
        UserBO selectOne = userMapper.selectOne(wrapper);
        if (selectOne == null) return null;
        return BeanUtil.copyProperties(selectOne, UserEntity.class);
    }

    @Nullable
    @Override
    public UserEntity findByMobile(String mobile, String company) {
        if (StringUtils.isBlank(mobile)) return null;
        Wrapper<UserBO> wrapper = Wrappers.lambdaQuery(UserBO.class)
                .eq(UserBO::getMobile, mobile)
                .eq(UserBO::getCompanyNo, company);
        UserBO selectOne = userMapper.selectOne(wrapper);
        if (selectOne == null) return null;
        return BeanUtil.copyProperties(selectOne, UserEntity.class);
    }

    @Nullable
    @Override
    public UserEntity findByOpenId(String openId, String company) {
        if (StringUtils.isBlank(openId)) return null;
        Wrapper<UserBO> wrapper = Wrappers.lambdaQuery(UserBO.class)
                .eq(UserBO::getOpenId, openId)
                .eq(UserBO::getCompanyNo, company);
        UserBO selectOne = userMapper.selectOne(wrapper);
        if (selectOne == null) return null;
        return BeanUtil.copyProperties(selectOne, UserEntity.class);
    }

    @Override
    public boolean save(UserEntity userEntity) {
        if (userEntity == null) return false;
        UserBO userBO = BeanUtil.copyProperties(userEntity, UserBO.class);
        int insertResult = userMapper.insert(userBO);
        if (insertResult <= 0) return false;
        BeanUtil.copyProperties(userBO, userEntity);
        return true;
    }

    @Override
    public boolean saveBatchRole(List<UserRoleBO> userRoleBOList) {
        userRoleMapper.insert(userRoleBOList);
        return userRoleBOList.stream().noneMatch(bo -> bo.getId() == null);
    }

    @Override
    public void deleteUserRoleByUserId(Long userId) {
        Wrapper<UserRoleBO> wrapper = Wrappers.lambdaQuery(UserRoleBO.class)
                .eq(UserRoleBO::getUserId, userId);
        userRoleMapper.delete(wrapper);
    }

    @Override
    public List<UserRoleBO> findUserRoleListByRoleId(Long roleId) {
        Wrapper<UserRoleBO> wrapper = Wrappers.lambdaQuery(UserRoleBO.class)
                .eq(UserRoleBO::getRoleId, roleId);
        return userRoleMapper.selectList(wrapper);
    }

    private Wrapper<UserBO> getWrapper(UserEntity entity) {
        QueryWrapper<UserBO> wrapper = Wrappers.query(UserBO.class);

        // 角色ID查询
        if (entity.getRoleId() != null) {
            List<UserRoleBO> userRoleBOList = this.findUserRoleListByRoleId(entity.getRoleId());
            if (CollUtil.isNotEmpty(userRoleBOList)) {
                wrapper.lambda().in(UserBO::getId, userRoleBOList.stream().map(UserRoleBO::getUserId).toList());
            } else {
                return null;
            }
        }

        // 部门No查询
        if (StringUtils.isNotBlank(entity.getDeptNo())) {
            List<DeptPostUserBO> userRoleBOList = deptRepository.findDeptPostUserListByDeptNo(entity.getDeptNo());
            if (CollUtil.isNotEmpty(userRoleBOList)) {
                wrapper.lambda().in(UserBO::getId, userRoleBOList.stream().map(DeptPostUserBO::getUserId).toList());
            } else {
                return null;
            }
        }

        return wrapper.lambda()
                .eq(StringUtils.isNotBlank(entity.getUsername()), UserBO::getUsername, entity.getUsername())
                .eq(StringUtils.isNotBlank(entity.getOpenId()), UserBO::getOpenId, entity.getOpenId())
                .eq(StringUtils.isNotBlank(entity.getSex()), UserBO::getSex, entity.getSex())
                .eq(entity.getDataState() != null, UserBO::getDataState, entity.getDataState())
                .likeRight(StringUtils.isNotBlank(entity.getMobile()), UserBO::getMobile, entity.getMobile())
                .likeRight(StringUtils.isNotBlank(entity.getEmail()), UserBO::getEmail, entity.getEmail())
                .likeRight(StringUtils.isNotBlank(entity.getNickName()), UserBO::getNickName, entity.getNickName())
                .likeRight(StringUtils.isNotBlank(entity.getRealName()), UserBO::getRealName, entity.getRealName())
                .orderByDesc(UserBO::getCreatedTime);
    }
}
